import json
from django.http import JsonResponse
from django.views import View
from books.models import Books


class BooksView(View):
    def get(self, request):
        books = Books.objects.filter(is_delete=False)
        book_list = books.values('id','btitle','bpub_date','bread','bcomment')
        book_list = list(book_list)
        data = {
            "code": 0,
            "msg": "success",
            "books": book_list
        }
        return JsonResponse(data)

    def post(self, request):
        body_json = request.body.decode()
        body_dict = json.loads(body_json)
        btitle = body_dict.get('btitle')
        bpub_date = body_dict.get('bpub_date')
        bread = body_dict.get('bread')
        bcomment = body_dict.get('bcomment')
        book = Books(btitle=btitle, bpub_date=bpub_date, bread=bread, bcomment=bcomment)
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})

    def put(self, request):
        body_json = request.body.decode()
        body_dict = json.loads(body_json)
        id = body_dict.get('id')
        btitle = body_dict.get('btitle')
        bpub_date = body_dict.get('bpub_date')
        bread = body_dict.get('bread')
        bcomment = body_dict.get('bcomment')
        book = Books.objects.get(id=id)
        book.btitle = btitle
        book.bpub_date = bpub_date
        book.bread = bread
        book.bcomment = bcomment
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})

    def delete(self, request):
        id = request.GET.get('id')
        book = Books.objects.get(id=id)
        book.is_delete = True
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})